<template>
  <div id="content" :style="{height:contentHeight+'px'}">
    <Card class="r-n-fs-c">
      <Select style="width: 240px;" v-model="typeSelect" placeholder="设施类型选择">
        <Option value="danger">险情类型</Option>
        <Option value="pileCard">桩牌类型</Option>
        <Option value="generalFacilities">通用设施类型</Option>
        <Option value="highConsequenceArea">高后果区类型</Option>
        <Option value="constructionUnits">施工作业区类型</Option>
        <Option value="camera">监控摄像头类型</Option>
      </Select>
      <Button @click="selectPageList()" type="primary" style="width: 100px;margin-left: 5px;">查询</Button>
      <Button @click="createType" type="primary" style="width: 100px;margin-left: 5px;">类型添加</Button>
    </Card>
    <Divider/>
    <div v-if="showModule === 1">
      <Table id="card-list-info-table" class="table" stripe
             border
             show-header
             highlight-row
             :loading="isLoading"
             :columns="tableColumns"
             :data="dataList">
      </Table>
      <Divider/>
      <Card style="margin-bottom: 15px;">
        <Page class="r-w-c-c"
              style="width: 100%"
              class-name="card-list-info-page"
              :total="page.total"
              :current="page.pageNum"
              :page-size="page.pageSize"
              @on-change="onPageChange"
              @on-page-size-change="onPageSizeChange"
              show-elevator
              show-sizer
              show-total/>
      </Card>
    </div>
    <div v-if="showModule === 2"></div>
    <Modal v-model="modalTip" width="360">
      <p slot="header" style="color:#f60;text-align:center">
        <Icon type="ios-information-circle"></Icon>
        <span>操作确认</span>
      </p>
      <div style="text-align:center">
        <p>{{ modalTipContent }}</p>
      </div>
      <div slot="footer">
        <Button type="error" size="large" long :loading="modalLoading" @click="modalTipOk">确认操作</Button>
      </div>
    </Modal>
    <Modal v-model="isCreateTypeShow" :title="modalTitle">
      <Form ref="selectFormRule" :rules="ruleValidate" :model="selectForm"
            style="margin-left: 0;width: 100%;">
        <label class="r-n-fs-c item-input">
          <span class="item-input-span">类型名称</span>
          <FormItem prop="name">
            <Input placeholder="类型名称" v-model="selectForm.name"/>
          </FormItem>
        </label>
        <label class="r-n-fs-c item-input">
          <span class="item-input-span">Icon</span>
          <FormItem prop="icon">
            <div class="r-n-fs-c" style="width: 100%;">
              <img v-if="selectForm.icon !== null && selectForm.icon !== undefined" :src="selectForm.icon" alt="类型ICON"
                   style="height: 40px;">
              <Upload
                  style="display: inline-block;"
                  paste
                  name="file"
                  :data=fileUploadParam
                  :headers="headers"
                  accept="['image/jpg','image/jpeg','image/png','image/ico','image/icon']"
                  :format="['jpg','jpeg','png','ico','icon']"
                  :show-upload-list="false"
                  :before-upload="imageUploadBefore"
                  :on-success="imageUploadSuccess"
                  :on-format-error="imageUploadFormatError"
                  :on-error="imageUploadError"
                  :action="host+url.file_upload">
                <Button :style="{width:'42px',padding: 0,marginLeft: (selectForm.icon === null || selectForm.icon === undefined) ? '':'10px'}">
                  <div style="width: 42px;height:32px;line-height: 32px;font-size:20px!important;text-align:center;"
                       class="iconfont icon-wenjianshangchuan"></div>
                </Button>
              </Upload>
            </div>
          </FormItem>
        </label>
      </Form>
      <div slot="footer">
        <Button type="text" @click="isCreateTypeShow=false">取消</Button>
        <Button type="primary" @click="modalOk()">提交</Button>
      </div>
    </Modal>
  </div>
</template>

<script>

import {mapGetters, mapState} from "vuex"
import axios from "axios";

export default {
  name: "InfrastructureType",
  computed: {
    ...mapState(["url", "host", "resourceHost", "realSideWidth"]),
    ...mapGetters(["contentWidth", "contentHeight"]),
  },
  data() {
    return {
      typeSelect: "danger",
      searchKey: null,
      showModule: 1,
      searchValue: null,
      btnLoading: false,
      isLoading: false,
      modalTip: false,
      modalTipContent: null,
      modalLoading: false,
      isCreateTypeShow: false,
      isPageSizeChanging: false,
      modalTitle: '类型添加',
      modalTitleData: null,
      operatorType: ['类型添加','类型更新'],
      fileUploadParam: {
        category: 15,
        projectId: 1
      },
      headers: {
        'u-projectId': null,
        'u-uid': null,
        'u-token': null,
      },
      selectForm: {
        id: null,
        name: null,
        icon: null,
        newIconPath: null
      },
      page:{
        total: 0,
        pageSize: 10,
        pageNum: 1,
        descParams:'id'
      },
      ruleValidate: {
        name: [
          {required: true, type: 'string', message: '类型名称不能为空', trigger: 'change'},
          { min: 2, message: '类型名称不能少于2个字符', trigger: 'change'},
          { max: 5, message: '类型名称不能超过5个字符', trigger: 'change'}
        ]
      },
      typeColumns:[
        {
          title: '类型ID',
          key: 'id',
          width: 150,
          minWidth: 100,
          resizable: true,
          align: "center",
          ellipsis: true,
          sortable: true,
        },
        {
          title: '类型名称',
          key: 'name',
          resizable: true,
          minWidth: 180,
          align: "center"
        },
        {
          title: '图标',
          key: 'icon',
          resizable: true,
          minWidth: 180,
          align: "center",
          render: this.imageRender
        },
        {
          title: '操作',
          resizable: true,
          minWidth: 150,
          align: "center",
          render: this.operatorRenderFunction
        }
      ],
      dangerTypeColumns:[
        {
          title: '类型ID',
          key: 'id',
          width: 150,
          minWidth: 100,
          resizable: true,
          align: "center",
          ellipsis: true,
          sortable: true,
        },
        {
          title: '类型名称',
          key: 'typeName',
          resizable: true,
          minWidth: 180,
          align: "center"
        },
        {
          title: '图标',
          resizable: true,
          minWidth: 180,
          align: "center",
          render:function (createElement, data) {
            let {icon} = data.row;
            return createElement('img', {
              style: {
                height: '25px'
              },
              attrs: {
                src: icon
              },
            });
          },
        },
        {
          title: '操作',
          resizable: true,
          minWidth: 150,
          align: "center",
          render: this.operatorRenderFunction
        }
      ],
      tableColumns:[],
      dataList: [],
      projectList: [],
      searchParamList: [
        {
          key: "id",
          show: "任务ID",
        },
        {
          key: "taskNumber",
          show: "任务编号",
        },
        {
          key: "taskName",
          show: "任务名称(模糊匹配)",
        },
        {
          key: "uavId",
          show: "无人机ID",
        },
        {
          key: "uavName",
          show: "无人机名称",
        },
        {
          key: "userId",
          show: "飞手ID",
        }
      ]
    }
  },
  watch: {
    typeSelect:function (){
      this.dataList = [];
      this.selectPageList(this.page);
    }
  },
  created: function () {

  },
  mounted: function () {
    this.headers['u-projectId'] = localStorage.getItem('u-projectId');
    this.headers['u-uid'] = localStorage.getItem('u-uid');
    this.headers['u-token'] = localStorage.getItem('u-token');
    this.selectPageList(this.page);
  },
  methods: {
    imageUploadBefore() {
      this.$Spin.show({
        render: (h) => {
          return h('div', [
            h('Icon', {
              'class': 'demo-spin-icon-load',
              props: {
                type: 'ios-loading',
                size: 18
              }
            }),
            h('div', 'Loading')
          ])
        }
      });
    },
    imageUploadSuccess(response) {
      this.$Spin.hide();
      if (response.state === 200) {
        let {content} = response;
        this.selectForm.newIconPath = content;
        this.selectForm.icon = localStorage.getItem("resourceHost") + content;
        this.$Notice.success({
          title: "文件上传",
          desc: "文件上传成功,URL[" + content + "]",
          duration: 10
        })
      } else {
        let {message} = response;
        this.$Notice.error({
          title: "文件上传",
          desc: message,
          duration: 10
        })
      }
    },
    imageUploadFormatError(file) {
      this.$Spin.hide();
      this.$Notice.warning({
        title: '文件格式错误',
        desc: '文件 ' + file.name + ' 格式不正确，请上传 JPG 或 JPEG 或 PNG 或 ICO 格式文件！',
        duration: 10
      });
    },
    imageUploadError(error) {
      this.$Spin.hide();
      this.$Notice.error({
        title: "上传失败",
        desc: error,
        duration: 10
      })
    },
    imageRender(createElement, data) {
      let {icon} = data.row,self = this;
      return createElement('img', {
        style: {
          maxHeight: '30px',
          maxWidth: '150px',
          cursor: 'pointer'
        },
        attrs: {
          title: '点击查看大图',
          src: icon
        },
        on: {
          click: function () {
            self.$store.state.imageWindowUrl = icon;
            self.$store.state.isImageWindowShow = true;
          }
        }
      });
    },
    modalOk(){
      let isValidate = false;
      this.$refs['selectFormRule'].validate((valid) => {
        if (valid) {
          isValidate = true;
        }
      })
      if (this.modalTitle === this.operatorType[0]){
        if (!isValidate) {
          return;
        }
        this.isCreateTypeShow = !isValidate;
        this.insertType(this.selectForm);
      }else if (this.modalTitle === this.operatorType[1]){
        if (!isValidate) {
          return;
        }
        this.isCreateTypeShow = !isValidate;
        this.updateType(this.selectForm);
      }
    },
    createType(){
      this.modalTitle = this.operatorType[0];
      this.$refs['selectFormRule'].resetFields();
      this.isCreateTypeShow = true;
    },
    searchKeyClear(){
      let self = this;
      self.searchValue = null;
    },
    flightDurationRender(createElement,data){
      let self = this;
      let {flightDuration} = data.row;
      return createElement('span',self.timeUnitConversion(flightDuration,0));
    },
    timeUnitConversion(number,decimalPoint=0){
      let conversionFlow = 0;
      if(60 > number){
        conversionFlow = parseInt(number)+"秒";
      }else if(60 < number && number < (60 * 60)){
        conversionFlow = (number/60).toFixed(decimalPoint)+"分钟";
      }else if(number > (60 * 60)) {
        conversionFlow = (number/(60*60)).toFixed(decimalPoint)+"小时";
      }
      return conversionFlow;
    },
    onPageChange(changedPage) {
      this.page.pageNum = changedPage;
      !this.isPageSizeChanging ? this.selectPageList(this.page) : {};
    },
    onPageSizeChange(changedPageSize) {
      this.isPageSizeChanging = true;
      new Promise(resolve => {
        this.page.pageSize = changedPageSize;
        resolve(changedPageSize)
      }).then(() => {
        this.selectPageList(this.page);
        this.isPageSizeChanging = false;
      })
    },
    fileAnalyseOperator(){
      this.modalTitle = this.operatorType[1];
      this.modalTipContent = "将开始执行文件分析,该操作将执行较长时间,是否确认执行?"
      this.modalTip = true;
    },
    fileCleanOperator(){
      this.modalTitle = this.operatorType[2];
      this.modalTipContent = "将开始执行文件清理,该操作将执行较长时间,是否确认执行?"
      this.modalTip = true;
    },
    modalTipOk() {
      this.modalLoading = true;
      switch (this.modalTitle){
        case this.operatorType[1]:{
          this.modalLoading = false;
          this.modalTip = false;
          this.fileAnalyse();
        }break;
        case this.operatorType[2]:{
          this.modalLoading = false;
          this.modalTip = false;
          this.fileClean();
        }break;
      }
    },
    operatorRenderFunction(createElement, data) {
      let self = this;
      let {
        id,name,typeName,icon
      } = data.row;
      return createElement('Button', {
        'class': 'button-item',
        style: {
          width: '100px',
          border: '#5CADFF 1px dashed',
          color: '#5cadff'
        },
        attrs: {
          type: "dashed"
        },
        nativeOn: {
          click: function () {
            self.modalTitle = self.operatorType[1];
            if (self.typeSelect === 'danger'){
              self.selectForm = {
                id: id,
                name: typeName,
                icon,
              }
            }else {
              self.selectForm = {
                id: id,
                name: name,
                icon,
              }
            }
            self.isCreateTypeShow = true;
          }
        },
      }, self.operatorType[1])
    },
    selectPageList(selectForm) {
      let url;
      switch (this.typeSelect){
        case 'danger':{
          url = this.url.danger_type_list;
          this.tableColumns = this.dangerTypeColumns;
        } break;
        case 'pileCard':{
          url = this.url.pile_card_type_list;
          this.tableColumns = this.typeColumns;
        } break;
        case 'generalFacilities':{
          url = this.url.general_facilities_type_list;
          this.tableColumns = this.typeColumns;
        } break;
        case 'highConsequenceArea':{
          url = this.url.high_consequence_areas_type_list;
          this.tableColumns = this.typeColumns;
        } break;
        case 'constructionUnits':{
          url = this.url.construction_type_list;
          this.tableColumns = this.typeColumns;
        } break;
        case 'camera':{
          url = this.url.camera_type_list;
          this.tableColumns = this.typeColumns;
        } break;
        default:{
          url = this.url.danger_type_list;
        }
      }
      this.doSelectPageList(selectForm,url);
    },
    doSelectPageList(selectForm,url) {
      let self = this;
      let form = Object.assign({}, selectForm);
      form = Object.assign(form, self.page);
      if (self.searchKey !== null && self.searchValue !== null && self.searchValue !== ""){
        form[self.searchKey] = self.searchValue.trim();
      }
      self.isLoading = true;
      axios.get(url, {params: form}).then(function (response) {
        let {records,total} = response.data.content;
        self.page.total = total;
        self.dataList = records;
        self.isLoading = false;
      }).catch(function () {
        self.isLoading = false;
      });
    },
    insertType(selectForm){
      let self = this;
      let form = {};
      form["name"]= selectForm['name'];
      if (selectForm['newIconPath'] != null) {
        form["icon"] = selectForm['newIconPath'];
      }
      let url;
      if (this.typeSelect === undefined){
        this.$Message.error("111")
        return;
      }
      switch (this.typeSelect) {
        case "danger":{
          url = self.url.danger_type_insert;
        }break;
        case "pileCard":{
          url = self.url.pile_card_type_insert;
        }break;
        case "generalFacilities":{
          url = self.url.general_facilities_type_insert;
        }break;
        case "highConsequenceArea":{
          url = self.url.high_consequence_areas_type_insert;
        }break;
        case "constructionUnits":{
          url = self.url.construction_type_insert;
        }break;
        case "camera":{
          url = self.url.camera_type_insert;
        }break;
      }
      axios.post(url, form).then(function (response) {
        let {message, state} = response.data;
        if (state === 200) {
          self.selectPageList(self.page);
          self.$Message.success(message);
        } else {
          self.$Message.error(message);
        }
        selectForm['newIconPath'] = null
        self.$Spin.hide();
      });
    },
    updateType(selectForm){
      let self = this;
      let form = {};
      form["id"]= selectForm['id'];
      form["name"]= selectForm['name'];
      if (selectForm['newIconPath'] != null) {
        form["icon"] = selectForm['newIconPath'];
      }
      let url;
      switch (this.typeSelect) {
        case "danger":{
          url = self.url.danger_type_modify;
        }break;
        case "pileCard":{
          url = self.url.pile_card_type_modify;
        }break;
        case "generalFacilities":{
          url = self.url.general_facilities_type_modify;
        }break;
        case "highConsequenceArea":{
          url = self.url.high_consequence_areas_type_modify;
        }break;
        case "constructionUnits":{
          url = self.url.construction_type_modify;
        }break;
        case "camera":{
          url = self.url.camera_type_modify;
        }break;
      }
      axios.patch(url, form).then(function (response) {
        let {message, state} = response.data;
        if (state === 200) {
          self.selectPageList(self.page);
          self.$Message.success(message);
        } else {
          self.$Message.error(message);
        }
        selectForm['newIconPath'] = null
        self.$Spin.hide();
      });
    }
  }
}
</script>

<style scoped>
#content {
  background: #FFFFFF;
  padding: 15px;
  overflow: auto;
}

.item-input {
  height: 45px;
  line-height: 45px;
  margin-bottom: 10px;
}

.item-input-span {
  /*height: inherit;*/
  width: 120px;
}

.item-key {
  /*height: inherit;*/
  width: 150px;
}
.item-value {
  /*height: inherit;*/
  width: 50px;
}

.ivu-form-item-content {
  margin-left: 0 !important;
  position: relative;
  line-height: 32px;
  font-size: 14px;
}

.ivu-form-item {
  margin-bottom: 0;
  width: 100%;
}

.button-item {
  border: #19be6b 1px dashed;
  color: #19be6b;
}

.filter-item {
  margin: 0 5px;
}

.demo-spin-icon-load{
  animation: ani-demo-spin 1s linear infinite;
}
@keyframes ani-demo-spin {
  from { transform: rotate(0deg);}
  50%  { transform: rotate(180deg);}
  to   { transform: rotate(360deg);}
}
.demo-spin-col{
  height: 20px;
  position: relative;
}
</style>
